package com.control;

import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.model.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    private boolean isRight(User user, StringBuilder errorMassage) {
        boolean iserror = false;
        if (user.getUsername().isEmpty()) {
            errorMassage.append("用户名不能为空<br>");
            iserror = true;
        }
        if (user.getPasswd().isEmpty()) {
            errorMassage.append("密码不能为空<br>");
            iserror = true;
        }
        UserDao userDao = new UserDaoImpl();
        if (!userDao.hasUser(user)) {
            errorMassage.append("用户不存在<br>");
            iserror = true;
        }
        if (iserror == true) {
            return false;
        }
        return true;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String passwd = req.getParameter("passwd");
        User user = new User();
        user.setUsername(username);
        user.setPasswd(passwd);
        HttpSession httpSession = req.getSession();
        UserDao userDao = new UserDaoImpl();
        StringBuilder errorMassage = new StringBuilder();
        if (isRight(user, errorMassage)) {
            if (userDao.isPasswdRight(user)) {
                httpSession.setAttribute("loginUser", userDao.getLoginUserByUser(user));
                resp.sendRedirect("menu.jsp");
            } else {
                errorMassage.append("密码错误<br>");
                req.setAttribute("errorMassage", errorMassage);
                RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
                requestDispatcher.forward(req, resp);
            }
        } else {
            req.setAttribute("errorMassage", errorMassage);
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(req, resp);
        }
    }
}
